<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="80px">
    <el-form-item label="历史数据名称" prop="hisName" :class="{ 'is-required': true }" >
      <el-input v-model="dataForm.hisName" placeholder="历史数据名称"></el-input>
    </el-form-item>
    <el-form-item label="数据说明" prop="hisRemark" >
      <el-input v-model="dataForm.hisRemark" placeholder="数据说明"></el-input>
    </el-form-item>
    <el-form-item label="省份" prop="province">
      <el-select v-model="dataForm.province" clearable  placeholder="请选择">
        <el-option
          v-for="item in provinceList"
          :key="item.code"
          :label="item.name"
          :value="item.code">
        </el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="年度" prop="hisYear">
      <el-select v-model="dataForm.hisYear" clearable placeholder="请选择">
            <el-option label="2008年" value="2008年"></el-option>
            <el-option label="2009年" value="2009年"></el-option>
            <el-option label="2010年" value="2010年"></el-option>
            <el-option label="2011年" value="2011年"></el-option>
            <el-option label="2012年" value="2012年"></el-option>
            <el-option label="2013年" value="2013年"></el-option>
            <el-option label="2014年" value="2014年"></el-option>
            <el-option label="2015年" value="2015年"></el-option>
            <el-option label="2016年" value="2016年"></el-option>
            <el-option label="2017年" value="2017年"></el-option>
            <el-option label="2018年" value="2018年"></el-option>
            <el-option label="2019年" value="2019年"></el-option>
            <el-option label="2020年" value="2020年"></el-option>
            <el-option label="2021年" value="2021年"></el-option>
            <el-option label="2022年" value="2022年"></el-option>
            <el-option label="2023年" value="2023年"></el-option>
          </el-select>
    </el-form-item>
   <el-form-item label="模板" prop="tempId">
      <el-select v-model="dataForm.tempId" clearable placeholder="请选择" @change="loadTask">
        <el-option
          v-for="item in tempList"
          :key="item.tempId"
          :label="item.name"
          :value="item.tempId">
        </el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="任务名称" prop="taskId">
      <el-select v-model="dataForm.taskId" clearable placeholder="请选择">
        <el-option
          v-for="item in taskList"
          :key="item.id"
          :label="item.name"
          :value="item.id">
        </el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="上传文件" v-if="isShowUpload">
      <el-upload
        class="upload-demo"
        ref="upload"
        :action="actionUrl"
        :on-remove="handleRemove"
        :on-preview="handlePreview"
        :onError="uploadError"
        :onSuccess="uploadSuccess"
        :beforeUpload="beforeAvatarUpload"
        :file-list="fileList"
        :auto-upload="false"
        :headers="{token: this.$cookie.get('token')}">
        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
        <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
        <div slot="tip" class="el-upload__tip">只能上传xlsx文件，大小不能超过10MB</div>
      </el-upload>
      <a class='download' v-if="isShowDownload" :href='downloadhttp' download=""  title="下载">下载</a>
    </el-form-item>

    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import global_ from '@/components/tool/Global'

  export default {
    data () {
      return {
        visible: false,
        isShowUpload: true,
        isShowDownload: false,
        downloadhttp: '',
        serverFileUrl: global_.SERVER_FILE_URL,
        actionUrl: global_.SERVER_FILE_URL + "/frt/file/hisUpload",
        fileList: [],
        provinceList:[],
        tempList:[],
        taskList:[],
        dataForm: {
          id: 0,
          provinceName: '',
          hisYear: '',
          tempName: '',
          taskName: '',
          province: '',
          tempId: '',
          taskId: '',
          url: '',
          fileId: '',
          createTime: '',
          hisName: '',
          hisRemark: '',
        },
        dataRule: {
          hisName: [
            { required: true, message: '历史数据名称不能为空', trigger: 'blur' }
          ],
          province: [
            { required: true, message: '省份不能为空', trigger: 'blur' }
          ],
          hisYear: [
            { required: true, message: '年度不能为空', trigger: 'blur' }
          ],
          tempId: [
            { required: true, message: '模板不能为空', trigger: 'blur' }
          ],
          taskId: [
            { required: true, message: '任务名称不能为空', trigger: 'blur' }
          ]
        }
      }
    },
    methods: {
      init (id) {
        this.dataForm.id = id || 0
        this.visible = true
        this.fileList = []

        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.id) {

            this.$http({
              url: this.$http.adornUrl('/frt/task/selectTemp'),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              this.tempList = data.list
            }).then(()=>{
              this.$http({
                url: this.$http.adornUrl('/frt/district/select'),
                method: 'get',
                params: this.$http.adornParams({
                  'level': 1,
                  'flag': 'history'
                })
              }).then(({data}) => {
                this.provinceList = data.list;
              })
            }).then(()=>{
              this.$http({
              url: this.$http.adornUrl(`/frt/history/info/${this.dataForm.id}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.dataForm.hisName = data.history.hisName
                this.dataForm.hisRemark = data.history.hisRemark
                this.dataForm.provinceName = data.history.provinceName
                this.dataForm.hisYear = data.history.hisYear
                this.dataForm.tempName = data.history.tempName
                this.dataForm.taskName = data.history.taskName
                this.dataForm.province = data.history.province
                this.dataForm.tempId = data.history.tempId
                this.dataForm.taskId = data.history.taskId
                this.loadTask(this.dataForm.tempId)
                
                this.dataForm.url = data.history.url
                this.dataForm.fileId = data.history.fileId
                this.dataForm.createTime = data.history.createTime
                this.isShowUpload = true;
                this.isShowDownload = true;
                this.downloadhttp = this.serverFileUrl + '/frt/file/hisDownload?fileId='+data.history.fileId+'&token='+this.$cookie.get('token')
              }
            })
            })
          }else{
            this.$http({
              url: this.$http.adornUrl('/frt/task/selectTemp'),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              this.tempList = data.list
            }).then(()=>{
              this.$http({
                url: this.$http.adornUrl('/frt/district/select'),
                method: 'get',
                params: this.$http.adornParams({
                  'level': 1,
                  'flag': 'history'
                })
              }).then(({data}) => {
                this.provinceList = data.list;
              })
            })
          }
        })
      },
      // 表单提交
      dataFormSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            if(this.fileList.length == 0){
              this.$message.error('请先上传文件！')
              return false;
            }

            this.$http({
              url: this.$http.adornUrl(`/frt/history/${!this.dataForm.id ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                'hisName': this.dataForm.hisName,
                'hisRemark': this.dataForm.hisRemark,
                'id': this.dataForm.id || undefined,
                'provinceName': this.dataForm.provinceName,
                'hisYear': this.dataForm.hisYear,
                'tempName': this.dataForm.tempName,
                'taskName': this.dataForm.taskName,
                'province': this.dataForm.province,
                'tempId': this.dataForm.tempId,
                'taskId': this.dataForm.taskId,
                'url': this.dataForm.url,
                'fileId': this.dataForm.fileId,
                'createTime': this.dataForm.createTime,
                'url': this.fileList.length > 0 ? this.fileList[0].url : '',
                'fileId': this.fileList.length > 0 ? this.fileList[0].fileId : ''
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      },
      submitUpload() {
        this.$refs.upload.submit();
      },
      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      handlePreview(file) {

        console.log(file);
      },
      // 上传成功后的回调
      uploadSuccess (response, file, fileList) {
        this.$message({
          message: response.msg,
          type: 'success',
          duration: 1500,
          onClose: () => {
          }
        });
        this.isShowDownload = true;
        this.downloadhttp = this.serverFileUrl + '/frt/file/hisDownload?fileId='+response.fileId+'&token='+this.$cookie.get('token')
        this.fileList = [{name: response.name, url: response.url, fileId: response.fileId}]
      },
      // 上传错误
      uploadError (response, file, fileList) {
        this.isShowDownload = false;
        this.$message.error('上传失败，请重试！')
      },
      // 上传前对文件的大小的判断
      beforeAvatarUpload (file) {
        const extension2 = file.name.split('.')[1] === 'xlsx'
        const isLt2M = file.size / 1024 / 1024 < 10
        if (!extension2) {
          this.$message.error('上传模板只能是xlsx格式!')
        }
        if (!isLt2M) {
          this.$message.error('上传模板大小不能超过 10MB!')
        }
        return extension2 && isLt2M
      },
      showUpload(curVal){
        if(curVal == 'forestry_monitor'){
          this.isShowUpload = true;
        }else{
          this.isShowUpload = false;
        }
      },
      loadTask(curVal){
        this.taskList = [];
        this.$http({
            url: this.$http.adornUrl('/frt/task/select'),
            method: 'get',
            params: this.$http.adornParams({
              'tempId': curVal
            })
          }).then(({data}) => {
            this.taskList = data.list;
          })
      }
    }
  }
</script>
